//var LoadingModal = $("<div id='loading' class='modal'><img src='../resources/css/image/loading.gif' /></div>");

//加载content区域的数据
function loadContent(uri, c, type) {
    LOADING.show();
    if ("post" == type) {
        $.post(uri, c, function (result) {
            if (result.indexOf("j_spring_security_check") > 0) {
                // session过期时重新返回到登陆页面
                window.location.reload();
                return true;
            }
            if (c) {
                if (c.toString().indexOf("fieldName") > 0) {
                    $("[oper=content]").attr("history", uri + "?" + c);
                } else {
                    var history = $("[oper=content]").attr("history");
                    if (history) {
                        var huri = history.substring(0, history.indexOf("?"));
                        var hc = history.substring(history.indexOf("?") + 1);
                        loadContent(huri, hc, "post");
                        return false;
                    }
                }
            }
            $("[oper=content]").empty().html(result);
            // 日期控件
            $("[datepicker]").datepicker({
                dateFormat: "yy-mm-dd",
                monthNames: [ "- 01月", "- 02月", "- 03月", "- 04月", "- 05月", "- 06月", "- 07月", "- 08月", "- 09月", "- 10月", "- 11月", "- 12月" ],
                showMonthAfterYear: true,
                changeMonth: true,
                changeYear: true
            });
            LOADING.hide();
        }, "html");
    } else {
        $.get(uri, c, function (result) {
            if (result && result.indexOf("j_spring_security_check") > 0) {
                // session过期时重新返回到登陆页面
                window.location.reload();
                return true;
            }
            if (c) {
                if (c.toString().indexOf("fieldName") > 0) {
                    $("[oper=content]").attr("history", uri + "?" + c);
                } else {
                    var history = $("[oper=content]").attr("history");
                    if (history) {
                        var huri = history.substring(0, history.indexOf("?"));
                        var hc = history.substring(history.indexOf("?") + 1);
                        loadContent(huri, hc, "post");
                        return false;
                    }
                }
            }
            $("[oper=content]").empty().html(result);
            // 日期控件
            $("[datepicker]").datepicker({
                dateFormat: "yy-mm-dd",
                monthNames: [ "- 01月", "- 02月", "- 03月", "- 04月", "- 05月", "- 06月", "- 07月", "- 08月", "- 09月", "- 10月", "- 11月", "- 12月" ],
                showMonthAfterYear: true,
                changeMonth: true,
                changeYear: true
            });
            LOADING.hide();
        }, "html");
    }
};
$(function () {

    $(document).on("keypress", function (e) {
        if (e.keyCode == 8) {
            var tag = e.target.tagName;
            if (tag.length > 1 && "INPUT,TEXTAREA".indexOf(tag) != -1) {
                return true;
            } else {
                return false;
            }
        }

    });

    // 给地址栏中的地址加上一个“#”
    location.href = location.href + "#";
    $(document).ajaxError(function (e, xhr, opt) {
        LOADING.hide();
        if (xhr.status == 403) {
            // alert("Error requesting " + opt.url + ": " + xhr.status + " " + xhr.statusText);
            // return;
            alert("操作超时，请重新登陆！");
            window.location.reload();
            location.href = "./login.jsp";
            return;
        } else if (xhr.status == 404) {
            loadContent("denied.jsp");
            return;
        } else if (xhr.status == 200) {
            //alert(xhr.status);
            //loadContent("denied.jsp");
            alert("系统错误，请联系管理员!");
        }
    });
    // jquery ajax不缓存
    $.ajaxSetup({
        cache: false
    });
    // $("#myModal").jquerymove();
    $.post("frame/html", function (resutl) {
        $("#div").html(resutl);
    }, "html");
    $("[oper]").each(function () {
        var uri = $(this).attr("href");
        var self = $(this);
        if (uri != "") {
            $.post(uri, function (result) {
                self.html(result);
            }, "html");
        }
    });
    // oper="accordion"中的a标签点击事件
    $("[oper=accordion] a[item]").die().live("click", function () {
        var uri = $(this).attr("href");
        if (uri != "") {
            try {
                // 菜单跳转时清掉history
                $("[oper=content]").removeAttr("history");
                loadContent(uri);
            } catch (e) {
                alert("error");
            }
        }
        return false;
    });
    // content中的a标签点击事件
    $("[oper=content] a").die().live("click", function () {
        var deny = $(this).attr("deny");
        if (deny == "not") {
            return true;
        }
        var uri = $(this).attr("href");
        if (uri && uri != "") {
            if (uri.indexOf("jumpPage") > 0) {
                return true;
            } else if (uri.indexOf("sort") > 0) {
                return true;
            } else {
                var confirms = $(this).attr("confirm");
                if (confirms) {
                    if (confirm(confirms)) {
                        loadContent(uri, true);
                    }
                } else {
                    loadContent(uri);
                }
            }
        }
        return false;
    });
    // 返回
    $("[oper=content] [back]").die().live("mousedown", function () {
        if ($(this).attr("back") == "back") {
            var history = $("[oper=content]").attr("history");
            if (history) {
                var huri = history.substring(0, history.indexOf("?"));
                var hc = history.substring(history.indexOf("?") + 1);
                loadContent(huri, hc, "post");
            } else {
                var backMenu = $(".icon-arrow-right").parent().find("a");
                backMenu.click();
            }
            return false;
        }
    });
    $("[oper=content] [onclick]").die().live("mousedown", function () {
        if ($(this).attr("onclick").toString().indexOf("back") > 0) {
            var history = $("[oper=content]").attr("history");
            if (history) {
                var huri = history.substring(0, history.indexOf("?"));
                var hc = history.substring(history.indexOf("?") + 1);
                loadContent(huri, hc, "post");
            } else {
                var backMenu = $(".icon-arrow-right").parent().find("a");
                backMenu.click();
            }
            return false;
        }
    });
    // content中的form提交
    $("form").die().live("submit", function () {
        var deny = $(this).attr("deny");
        if (deny == "not") {
            return true;
        }
        var c = $(this).serialize();
        var uri = $(this).attr("action");
        loadContent(uri, c, "post");
        return false;
    });

    $("#closeMenu").toggle(function () {
        var _self = $(this);
        $(".iaccordion").fadeOut(500, function () {
            $(".icontent").css("width", "99.5%");
            _self.text("展开菜单");
        });

    }, function () {
        $(this).text("收起菜单");
        $(".icontent").css("width", "84.5%");
        $(".iaccordion").fadeIn(500, function () {
        });
    });

});
var msgAlert = {
    modalDom: "#myModal_msg",
    msgDom: "#myModal_msg .modal_msg",
    show: function (msg) {
        $(this.msgDom).html(msg);
        $(this.modalDom).modal("show");
    },
    close: function () {
        $(this.modalDom).modal("hide");
    }

};
jQuery.validator.addMethod("mobile", function (value, element) {
    var length = value.length;
    var mobile = /^(((13[0-9]{1})|(18[0-9]{1})|(15[0-9]{1}))+\d{8})$/
    return this.optional(element) || (length == 11 && mobile.test(value));
}, "手机号码格式错误");

jQuery.validator.addMethod("phone", function (value, element) {
    var length = value.length;
    //var mobile = /^(((13[0-9]{1})|(15[0-9]{1}))+\d{8})$/
    var mobile = /^((1)+\d{10})$/
    var isMobile = this.optional(element) || (length == 11 && mobile.test(value));
    if (!isMobile) {
        var tel = /^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/;
        return this.optional(element) || (tel.test(value));
    } else {
        return true;
    }
}, "电话号码格式错误");

jQuery.validator.addMethod("chinese", function (value, element) {
    var chinese = /^[\u4e00-\u9fa5]+$/;
    return this.optional(element) || (chinese.test(value));
}, "只能输入中文");

jQuery.validator.addMethod("isIdCardNo", function (value, element) {
    return this.optional(element) || isIdCardNo(value);
}, "请正确输入您的身份证号码");

//邮政编码验证     
jQuery.validator.addMethod("zipCode", function (value, element) {
    var tel = /^[0-9]{6}$/;
    return this.optional(element) || (tel.test(value));
}, "邮政编码格式错误");

//正整数
jQuery.validator.addMethod("greaterThanZero", function (value, element) {
    return this.optional(element) || (parseFloat(value) > 0);
}, "数量必须大于0");

//增加身份证验证
function isIdCardNo(num) {
    var factorArr = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1);
    var parityBit = new Array("1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2");
    var varArray = new Array();
    var intValue;
    var lngProduct = 0;
    var intCheckDigit;
    var intStrLen = num.length;
    var idNumber = num;
    // initialize
    if ((intStrLen != 15) && (intStrLen != 18)) {
        return false;
    }
    // check and set value
    for (i = 0; i < intStrLen; i++) {
        varArray[i] = idNumber.charAt(i);
        if ((varArray[i] < '0' || varArray[i] > '9') && (i != 17)) {
            return false;
        } else if (i < 17) {
            varArray[i] = varArray[i] * factorArr[i];
        }
    }
    if (intStrLen == 18) {
        //check date
        var date8 = idNumber.substring(6, 14);
        if (isDate8(date8) == false) {
            return false;
        }
        // calculate the sum of the products
        for (i = 0; i < 17; i++) {
            lngProduct = lngProduct + varArray[i];
        }
        // calculate the check digit
        intCheckDigit = parityBit[lngProduct % 11];
        // check last digit
        if (varArray[17] != intCheckDigit) {
            return false;
        }
    }
    else {        //length is 15
        //check date
        var date6 = idNumber.substring(6, 12);
        if (isDate6(date6) == false) {
            return false;
        }
    }
    return true;
}

function isDate6(sDate) {
    if (!/^[0-9]{6}$/.test(sDate)) {
        return false;
    }
    var year, month, day;
    year = sDate.substring(0, 4);
    month = sDate.substring(4, 6);
    if (year < 1700 || year > 2500) return false
    if (month < 1 || month > 12) return false
    return true
}

function isDate8(sDate) {
    if (!/^[0-9]{8}$/.test(sDate)) {
        return false;
    }
    var year, month, day;
    year = sDate.substring(0, 4);
    month = sDate.substring(4, 6);
    day = sDate.substring(6, 8);
    var iaMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    if (year < 1700 || year > 2500) return false
    if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) iaMonthDays[1] = 29;
    if (month < 1 || month > 12) return false
    if (day < 1 || day > iaMonthDays[month - 1]) return false
    return true
}


var LOADING = {
    show: function () {
        $("#LODAING").modal("show");
    },
    hide: function () {
        $("#LODAING").modal("hide");
    }
}
var MapModel = {
    show: function (url) {
        if (url.indexOf("?") > 0) {
            url += "&t=" + new Date().getTime()
        } else {
            url += "?_" + new Date().getTime();
        }
        $("#MapModel iframe").attr("src", url);
        $("#MapModel").modal("show");
    },
    hide: function () {
        $("#MapModel").modal("hide");
    }
}

var UploadModel = {
    show: function (url) {
        if (url.indexOf("?") > 0) {
            url += "&t=" + new Date().getTime()
        } else {
            url += "?_" + new Date().getTime();
        }
        $("#UploadModel iframe").attr("src", url);
        $("#UploadModel").modal("show");
    },
    hide: function () {
        $("#UploadModel").modal("hide");
    }
}

var ChangeStatusModel = {
	    show: function (url,callbak) {
	        if (url.indexOf("?") > 0) {
	            url += "&t=" + new Date().getTime()
	        } else {
	            url += "?_" + new Date().getTime();
	        }
	        $("#ChangeStatusModel iframe").attr("src", url);
	        $("#ChangeStatusModel").modal("show").on("hidden",function() {
                if(callbak) {
                    callbak();
                }
            });
	    },
	    hide: function () {
	        $("#ChangeStatusModel").modal("hide");
	    }
	}

$(function () {


    window.progressModal = {
        modal: $("#progressModal"),
        bar: $("#progressModal .bar"),
        txt: $("#progressModal #percent"),
        clearTime: 0,
        reset: function (percentName) {
            var _self = this;
            _self.txt.html("0%");
            _self.bar.css("width", "1%");
            $.get("progress?percentName=" + percentName + "&reset=true&t=" + new Date().getTime(), function (data) {
            });
        },
        /**
         *
         * @param percentName
         * @param time
         * @param callback
         */
        show: function (percentName, time, callback) {
            var _self = this;
            _self.reset(percentName);
            if (_self.modal && percentName && time) {
                _self.clearTime = setInterval(function () {
                    $.post("progress?percentName=" + percentName + "&t=" + new Date().getTime(), function (data) {
                        if (data) {
                            if(data) {
                                _self.txt.html(data + "%");
                                _self.bar.css("width", data + "%");
                            }
                            console.log(data);
                            if (data >= 100 || data < 0) {
                                setTimeout(function () {
                                    _self.hide();
                                }, 200);
                                clearInterval(_self.clearTime);
                            }
                        }
                    },'html');
                }, time);
                $("#LODAING").css("z-index", 1040);
                _self.modal.modal("show").unbind("hidden").on("hidden", function () {
                    clearInterval(_self.clearTime);
                    _self.bar.css("width", "0%");
                    if (callback) {
                        callback();
                    }
                    $("#LODAING").css("z-index", 2000);
                });
            }
        },
        hide: function () {
            var _self = this;
            if (_self.modal) {
                _self.modal.modal("hide");
            }
        }
    }
});